<template>
  <div class="app-container">
    <div style="margin-bottom: 10px;display: flex;justify-content: space-between">
      <div style="font-size: 18px">
        <el-page-header @back="$router.back()" :content="cr.name">
        </el-page-header>
      </div>
      <div>
        <AButton type="primary" plain @click="addRow">新增行</AButton>
        <AButton type="primary" plain @click="handleExport" >导出excel</AButton>
      </div>
    </div>
    <el-table id="table" :data="tableData" v-loading="loading" style="width: 100%" @cell-dblclick="handleDbclick" height="calc(100vh - 135px)">
      <!--      <el-table-column label="序号" align="center" type="index" width="50" />-->
      <template v-for="item in tableHeader">
        <child-columns :key="item.id" :coloumn-header="item" align="center"
                       v-if="item.children && item.children.length"></child-columns>
        <el-table-column v-else :key="item.id" :label="item.label" :prop="item.fullLabel" align="center">
          <template slot-scope="scope">
                  <span v-if="!scope.row.edit">
                    <span>{{scope.row[item.fullLabel]}}</span>
                  </span>
            <template v-else>
              <!--文本-->
              <el-input placeholder="请输入" v-model="scope.row[item.fullLabel]" v-if="item.dataType === 'text'"/>
              <!--日期-->
              <el-date-picker style="width: 130px" clearable size="small" v-model="scope.row[item.fullLabel]" type="date"
                              value-format="yyyy-MM-dd" :default-value="new Date()"
                              placeholder="请选择" v-if="item.dataType === 'date'">
              </el-date-picker>
              <!--选项-->
              <el-select placeholder="请选择" v-model="scope.row[item.fullLabel]" v-if="item.dataType === 'select'">
                <el-option
                    v-for="l in item.dataOptions.split(',')"
                    :key="l"
                    :label="l"
                    :value="l"
                />
              </el-select>
            </template>
          </template>
        </el-table-column>
      </template>
      <el-table-column v-if="editing" label="操作" align="center" width="150px">
        <template slot-scope="scope">
          <AButton v-if="scope.row.edit" type="text" class="orange-button" @click="handleSave(scope.row)">
            保存
          </AButton>
          <AButton v-if="scope.row.edit" type="text" class="orange-button" @click="handleCancel(scope.row)">
            取消
          </AButton>
          <AButton v-if="scope.row.edit" type="text" class="orange-button" @click="handleDelete(scope.row)">
            删除
          </AButton>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
  import {
    getCapitalRaising,
    editCrData,
    delCrData,
    addCrData,
  } from '@/api/business/capitalRaising'
  import ChildColumns from './childColumns'
  import table2excel from '@/api/tool/excel'
  import * as XLSX from 'xlsx/xlsx.mjs'
  import * as FileSaver from 'file-saver'
  import exportExcel from '@/utils/exportExcel.js'

  export default {
    name: 'capitalRaisingDetail',
    components: { ChildColumns },
    props: {
      crId: {
        type: [Number, String]
      }
    },
    data() {
      return {
        tableHeader: [],
        tableData: [],
        loading: false,
        editing: false,
        cr: {}
      }
    },
    created() {
      this.getData()
    },
    methods: {
      // 行双击
      handleDbclick(row) {
        if (this.editing == false) {
          let headerTypes = this.getHeaderType(this.tableHeader);
          let typeEnum = {};
          if(headerTypes.length > 0){
            headerTypes.forEach(item => {
              Object.assign(typeEnum,item)
            })
          }
          let keys = Object.keys(row);
          keys.forEach(key => {
            // 数据类型为日期 但格式不是日期格式的 清空数据 以免编辑行时候无法加载日期控件
            if(typeEnum[`${key}`] === 'date'){
              let reg = /^\d{4}[-](0?[1-9]|1[012])[-](0?[1-9]|[12][0-9]|3[01])$/
              if(!reg.test(row[`${key}`])){
                row[`${key}`] = null
              }
            }
          })
          row.edit = true
          this.editing = true
        }
      },
      // 获取表头类型
      getHeaderType(headers){
        let result = [];
        if(headers && headers.length > 0){
          headers.forEach(item => {
            let a = {};
            a[`${item.fullLabel}`] = item.dataType
            result.push(a);
            result.push(...this.getHeaderType(item.children))
          })
        }
        return result;
      },
      getData() {
        this.loading = true
        let id = this.$route.params.id?this.$route.params.id:this.crId
        getCapitalRaising(id).then(res => {
          this.cr = res.data;
          this.tableHeader = this.handleTree(res.data.header)
          this.headerTreeFormat(this.tableHeader);
          let temp = res.data.data
          this.tableData = temp.map(item => {
            let d = JSON.parse(item.crData);
            // this.$set(d,'edit',false)
            return {
              ...d,
              id: item.id
            }
          })
        }).finally(() => {
          this.loading = false
        })
      },
      //保存
      handleSave(row){
        this.editing = false
        row.edit = false;
        let data = JSON.parse(JSON.stringify(row));
        let param = {
          id: data.id,
        };
        Reflect.deleteProperty(data,'id')
        Reflect.deleteProperty(data,'edit')
        param.crData = JSON.stringify(data);
        if(param.id){
          // 新增数据
          // editXXXXX(param).then(res => {
          //   this.$message.success('保存成功')
          // }).catch(err => {
          //   this.$message.error(err)
          // })
        }else{
          // 新增数据
          // addXXXXX({
          //   ...param,
          //   crId: this.cr.id
          // }).then(res => {
          //   this.$message.success('保存成功')
          // }).catch(err => {
          //   this.$message.error(err)
          // })
        }
      },
      handleCancel(row){
        this.editing = false
        row.edit = false;
        this.tableData = this.tableData.filter(item => item.id)
      },
      handleDelete(row){
        this.editing = false
        row.edit = false;
        // 删除
        // delXXXXX(row.id).then(()=> {
        //   this.getData();
        // })
      },
      // 表头处理 应该用不上
      headerTreeFormat(treeData,parentNode){
        treeData.forEach(node => {
          if(!!node.parentId){
            node.fullLabel = parentNode.fullLabel + '_$#$_' + node.label;
          }else{
            node.fullLabel = node.label;
          }
          if(node.children && node.children.length > 0){
            this.headerTreeFormat(node.children,node);
          }
        })
      },
      // 新增行
      addRow(){
        if(this.editing){
          return;
        }
        this.tableData.push({
          edit: true
        })
        this.editing = true
      },
      // 根据 excel 的列名称 获取下标
      getExcelIndex(str){
        if (str == null) {
          return -1;
        }
        let index = -1;
        for (let i = 0; i < str.length; i++) {
          index += (str[i].charCodeAt(0) - 65 + 1) * (26 ** (str.length - i - 1)); // 当做26进制来算 AAA=111 26^2+26^1+26^0
        }
        return index ;// 从0开始的下标));
      },
      // 将sheet数据转成file
      async exportExcel(data) {
        // eslint-disable-next-line no-undef
        let merge = {};
        if(data.Sheets.Sheet1[`!merges`] && data.Sheets.Sheet1[`!merges`].length > 0){
          data.Sheets.Sheet1[`!merges`].forEach(item => {
            let res = {};
            res[`${item.s.r}_${item.s.c}`] = {
              r: item.s.r,
              c: item.s.c,
              rs: item.e.r - item.s.r + 1,
              cs: item.e.c - item.s.c + 1,
            };
            Object.assign(merge,res);
          })
        }
        let sheet = {
          config: {
            merge: merge
          }
        }
        Reflect.deleteProperty(data.Sheets.Sheet1,`!cols`)
        Reflect.deleteProperty(data.Sheets.Sheet1,`!fullref`)
        Reflect.deleteProperty(data.Sheets.Sheet1,`!merges`)
        Reflect.deleteProperty(data.Sheets.Sheet1,`!ref`)
        Reflect.deleteProperty(data.Sheets.Sheet1,`!rows`)
        console.log('data.Sheets.Sheet1___',data.Sheets.Sheet1)
        let keys = Object.keys(data.Sheets.Sheet1);
        let rIndex = [],cIndex = [];
        keys.forEach(key => {
          cIndex.push(key.replace(/[0-9]/g, ''))
          rIndex.push(key.replace(/[A-Z]/g, ''))
        })
        // 计算有多少行 多少列
        let rMax = Math.max(...rIndex.map(r => Number(r)));
        let cMax = Math.max(...cIndex.map(c => this.getExcelIndex(c)))
        // 生成对应行 列的矩阵
        let newData = [];
        for(let i = 0; i< rMax; i++){
          let r = [];
          for(let j = 0; j<= cMax; j++){
            r.push(null)
          }
          newData.push(r)
        }
        // 数据填充
        keys.forEach(key => {
          let val = data.Sheets.Sheet1[key];
          newData[Number(key.replace(/[A-Z]/g, '')) - 1][Number(this.getExcelIndex(key.replace(/[0-9]/g, '')))] = {
            ct: {fa: '@', t: 'g'},
            fc: "#000000",
            ff: "宋体",
            fs: 10,
            ht: 1,
            m: val.v,
            qp: 1,
            tb: 1,
            v: val.v,
            vt: 1,
          };
        })
        sheet.data = newData
        const exportData = await exportExcel([sheet])
        const blob = new Blob([exportData])
        const file = new File([blob], this.cr?.name || '文档.xlsx', { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
        return file
      },

      async handleExport(){
        /* generate workbook object from table */
        const xlsxParam = { raw: true } // 导出的内容只做解析，不进行格式转换
        const wb = XLSX.utils.table_to_book(document.querySelector('#table'), xlsxParam)


        /* 这里的导出也好使  */
        const wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' })
        try {
          FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), `提资计划-${this.cr.name}.xlsx`)
        } catch (e) {
          if (typeof console !== 'undefined') {
            console.log(e, wbout)
          }
        }
        return wbout

        /* 这里的导出是好使的  下载 */
        // const file = await this.exportExcel(wb)
        // if (window.navigator && window.navigator.msSaveBlob) {
        //   window.navigator.msSaveBlob(file, file.name)
        // } else {
        //   const a = document.createElement('a')
        //   a.download = file.name
        //   a.href = URL.createObjectURL(file)
        //   a.style.display = 'none'
        //   document.body.appendChild(a)
        //   a.click()
        //   document.body.removeChild(a)
        // }

      },
      getExcelHeader(){
        let eHeader = [];
        let data = this.tableHeader
        while (true){
          let line = [];
          let hasChild = false;
          let children = [];
          for(let i = 0;i<data.length ;i ++){
            if(data[i] && data[i].label){
              line.push(data[i].label);
            }else{
              line.push("");
            }
            if(data[i] && data[i].children && data[i].children.length > 0){
              for(let j = 1; j< data[i].children.length;j++){
                line.push("");
              }
              hasChild = true
              children.push(...data[i].children)
            }else{
              children.push({})
            }
          }
          eHeader.push(line);
          data = children;
          if(!hasChild){
            break;
          }
        }
        console.log(eHeader)
        return eHeader;
      }
    }
  }
</script>

<style scoped lang="scss">
  ::v-deep .el-input__inner{
    border: none;
    text-align: center;
  }
</style>
